import productimg from "../../../../imgs/product-1.jpg";
import CartCheckBox from "./CartCheckBox";
import AddNumber from "./AddNumber";
import EventEmitterUtils from "../../common/utils/EventEmitterUtils";
import HttpUtils from "../../common/utils/HttpUtils";
import StorageUtils from "../../common/utils/StorageUtils";
import InfoModal from "@page/common/modal/InfoModal";
import PopConfirm from "@ui/RJMart/popconfirm";
import Icon from "@ui/RJMart/icons";
import ImageWithError from "@page/common/comps/ImageWithError";
import CommonUtils from "@page/common/utils/CommonUtils";
// import Tip from "@ui/RJMart/tip";
import Tooltip from "@ui/RJMart/tooltip";
import dange from "@assets/dange.png";
import Popover from "@ui/RJMart/popover";
import CartProInfoExpire from "./CartProInfoExpire";

export default class CartProInfo extends React.Component {
    constructor(props) {
        super(props);
        const { info } = this.props || {};
        let isSelect = false;
        if (
            info.product &&
            $state.params[""] &&
            $state.params[""].indexOf(info.product.sn) > -1
        ) {
            isSelect = true;
            setTimeout(function() {
                EventEmitterUtils.emit("cartChoosedTotalCountChange", null);
            }, 200);
        }
        this.state = {
            isShowTip: false,
            isInteresting: false,
            message: "",
            selected: isSelect,
            count: global.hasLogin ? info.amount : info.count
        };
        this.suppId = info.product && info.product.suppId;
    }

    componentDidMount() {
        const { info } = this.props || {};
        if(global.hasLogin){
            this.isInterestProduct();
        }
        setTimeout(function() {
            if (info.product && $state.params[""] == info.product.sn) {
                // isSelect = true;
                EventEmitterUtils.emit("cartChoosedTotalCountChange", null);
            }
        }, 100);
        // this.suppId == "5" && this.priceAvailability();
        EventEmitterUtils.on("productSnsFocusOn", (list = []) => {
            if (this.props.info && this.props.info.product) {
                if (list.indexOf(this.props.info.product.sn) > -1) {
                    this.setState({ isInteresting: true });
                }
            }
        });
    }

    componentWillReceiveProps(nextProps) {
        this.isChecked(nextProps);
    }

    componentWillUnmount() {
        EventEmitterUtils.off("productSnsFocusOn");
    }

    isChecked(nextProps) {
        if (nextProps.for_list_header) {
            return;
        }
        if (!this.props.list_selected && nextProps.list_selected) {
            this.setState({
                selected: true
            });
            return;
        }

        if (this.props.list_selected && !nextProps.list_selected) {
            this.setState({
                selected: false
            });
            return;
        }
    }

    isShowListSelected() {
        const { index, showListSelected } = this.props;
        const listEles = document.querySelectorAll(
            `.cart-pro-item-content-${index}`
        );
        const checkedEles = document.querySelectorAll(
            `.cart-pro-item-content-${index} .cart-content-box-gouxuan1`
        );
        // console.log(checkedEles)
        if (listEles && checkedEles && listEles.length == checkedEles.length) {
            showListSelected();
        }
        EventEmitterUtils.emit("cartChoosedTotalCountChange", null);
    }

    getValues() {
        const { info } = this.props;

        if (global.hasLogin) {
            const { product, amount, id, countPrice, allowPurchase } = info;
            let {
                name,
                brandName,
                productNum,
                photo,
                specification,
                unifyPrice,
                price,
                sn,
                negotiatedPrice,
                sku,
                hasActivity,
                dangerousTag
            } = product;
            return {
                name,
                brandName,
                productNum,
                photo,
                specification,
                unifyPrice,
                price,
                amount,
                sn,
                cartId: id,
                negotiatedPrice,
                sku,
                hasActivity,
                countPrice,
                dangerousTag,
                allowPurchase
            };
        } else {
            let {
                count,
                productId,
                productNum,
                productName,
                productPhoto,
                productPrice,
                productSku,
                productSpec,
                sum,
                countPrice,
                dangerousTag
            } = info;
            return {
                name: productName,
                brandName: "",
                productNum: productNum,
                photo: productPhoto,
                specification: productSpec,
                unifyPrice: productPrice,
                price: productPrice,
                amount: count,
                sn: productId,
                cartId: null,
                negotiatedPrice: false,
                sku: productSku,
                hasActivity: false,
                countPrice,
                dangerousTag,
                allowPurchase: true
            };
        }
    }

    //删除购物车商品
    deleteShopCart(sn) {
        if (!global.hasLogin) {
            this.deleteCartLocal(sn);
            return;
        }

        HttpUtils.deleteShoppingCart([sn])
            .then(res => {
                // alert('删除成功')
                this.emitEvents();
            })
            .catch(err => {});
    }

    emitEvents() {
        EventEmitterUtils.emit("refreshCartData", null);
        setTimeout(() => {
            EventEmitterUtils.emit("cartChoosedTotalCountChange", null);
        }, 200);
    }

    //未登录时，删除本地记录
    deleteCartLocal(productId) {
        StorageUtils.deleteCartCount(productId);
        this.emitEvents();
    }

    shopCartCountChange(productId, curentCount) {
        if (!global.hasLogin) {
            const total = this.getTotalCount();
            localStorage.setItem("shopCartCount", total);
            StorageUtils.updateCartInfo(productId, curentCount);
        } else {
            HttpUtils.saveToShoppingCart(curentCount, productId, true)
                .then(res => {
                    console.log(res);
                })
                .catch(err => {
                    console.log(err);
                });
        }

        EventEmitterUtils.emit("updateShopCartNum", null);
    }

    getTotalCount() {
        let eleList = document.querySelectorAll(
            ".cart-pro-count-input-value-normal"
        );
        let count = 0;
        eleList &&
            eleList.forEach(ele => {
                count += ele.value - 0;
            });
        return count;
    }

    //获取货期西格玛
    priceAvailability() {
        let url = `/shop/store/product/priceAvailability`;
        let params = {
            productCode:
                this.props.info &&
                this.props.info.product &&
                this.props.info.product.productNum,
            quantity: this.state.count || 1
        };
        REST.post(url, params).then(
            data => {
                if (data.code == "1") {
                    this.setState({ message: data.data || "查询失败" });
                }
            },
            error => {}
        );
    }

    // 是否关注商品
    isInterestProduct() {
        let productId =
            this.props.info &&
            this.props.info.product &&
            this.props.info.product.sn;

        let url = `/store/api/user/buyer/isInterestProduct`;
        REST.post(url, { productSn: productId }).then(
            data => {
                this.setState({ isInteresting: data && data.isInteresting });
            },
            error => {}
        );
    }

    //关注取消商品
    interestProduct(sn) {
        let url = `/store/api/user/buyer/updateInterestProduct`;
        let params = {
            productSns: [sn],
            isInteresting: !this.state.isInteresting
        };
        REST.post(url, params).then(
            data => {
                this.setState({ isInteresting: params.isInteresting });
            },
            error => {}
        );
    }

    getCutLength(defaultLen,value){
       if(value){
           let letterLen=this.getEnglishLetterLen(value);
           let len=defaultLen+Math.floor(letterLen/2);
           return  len;
       }
       return defaultLen;
    }

    getEnglishLetterLen(val){
        if(val){
            if(/[a-z\(\)]/.test(val)){
                return val.match(/[a-z\(\)]/g).length;
            }
        }
        return 0;
    }

    render() {
        const {
            hasBottomLine,
            index,
            hideListSelected,
            info,
            suppId
        } = this.props;
        const {
            selected,
            count,
            modalMsg,
            message,
            isInteresting,
            isShowTip
        } = this.state;
        const {
            name,
            productNum,
            photo,
            specification,
            unifyPrice,
            price,
            amount,
            sn,
            cartId,
            negotiatedPrice,
            hasActivity,
            sku,
            countPrice,
            dangerousTag,
            allowPurchase
        } = this.getValues();

        if (!allowPurchase) {
            return (
                <div className={"cart-expire-item"}>
                    <CartProInfoExpire suppId={suppId} info={info} />
                </div>
            );
        }

        return (
            <div
                cartid={cartId}
                sn={sn}
                className={
                    selected
                        ? `cart-pro-item-content1 cart-pro-item-content-${index}`
                        : `cart-pro-item-content cart-pro-item-content-${index}`
                }
            >
                <CartCheckBox
                    selected={selected}
                    onClick={() => {
                        if (selected) {
                            hideListSelected();
                        }
                        this.setState(
                            {
                                selected: !selected
                            },
                            this.isShowListSelected
                        );
                    }}
                />

                <ImageWithError src={photo} style={{ width: 72, height: 72 }} />
                <div
                    className={
                        hasBottomLine
                            ? "cart-content-box-info-line"
                            : "cart-content-box-info"
                    }
                >
                    <div
                        onClick={() => {
                            window.open(
                                `#detail?productId=${sn}&suppId=${suppId}`
                            );
                        }}
                        className={"cart-pro-item-content-name"}
                    >
                        {Filter.cutString(name,CommonUtils.getCutLength(name,48),1) }
                        {dangerousTag &&
                        dangerousTag != "其他" &&
                        dangerousTag != "常规化学品" ? (
                            <div
                                style={{
                                    display: "inline-block",
                                    // marginTop: 6,
                                    marginLeft: 10
                                }}
                            >
                                <div className={"cart-dange-tag"}>
                                    <img src={dange} alt="" />
                                    <p>{dangerousTag}</p>
                                </div>
                            </div>
                        ) : null}
                    </div>

                    <p className={"cart-pro-item-content-p3"}>{productNum}</p>
                    <p className={"cart-pro-item-content-p4"}>
                        {Filter.cutString(specification, 20, 1)}
                    </p>
                    <div className={"cart-pro-item-content-p5"}>
                        {global.hasLogin?`￥${price.toFixed(2)}`:`登录可见`}
                        {hasActivity && (
                            <div>
                                <p
                                    className={
                                        "cart-pro-item-content-unifyPrice"
                                    }
                                >
                                    {" "}
                                    {global.hasLogin?`￥${unifyPrice.toFixed(2)}`:''}
                                </p>
                            </div>
                        )}
                        {negotiatedPrice && (
                            <div className={"cart-tejia-band1"}>
                                <p className={"cart-tejia-band1-p"}>低价推荐</p>
                            </div>
                        )}
                    </div>
                    <div
                        className={Uts.sc([
                            "cart-pro-item-content-p6",
                            this.suppId == "5" ? "" : "zen_m-r-45"
                        ])}
                    >
                        <AddNumber
                            defaultAmount={amount}
                            selected={selected}
                            setCount={count => {
                                info.amount = count;
                                this.setState(
                                    {
                                        count
                                    },
                                    () => this.shopCartCountChange(sn, count)
                                );
                            }}
                        />
                        {count >= sku && (
                            <p
                                className={
                                    selected && count > sku
                                        ? `cart-pro-item-content-sku cart-pro-item-content-sku-select`
                                        : "cart-pro-item-content-sku"
                                }
                            >
                                当前库存：{sku}
                            </p>
                        )}
                    </div>

                    {this.suppId == "5" && (
                        <div className="zen_ps-re">
                            {isShowTip && (
                                <Tip
                                    id={productNum}
                                    isShow={isShowTip}
                                    carNum={count}
                                    cb={isShow => {
                                        this.setState({ isShowTip: isShow });
                                    }}
                                />
                            )}
                            <span
                                className="zen_fs-12 zen_ps-re zen_t-6 zen_m-l-5 zen_cur-p zen_0093EB"
                                onClick={() => {
                                    this.setState({ isShowTip: true });
                                }}
                            >
                                查询货期
                            </span>
                        </div>
                    )}

                    <p
                        className={
                            selected
                                ? "cart-pro-item-content-p7-choose"
                                : "cart-pro-item-content-p7"
                        }
                    >
                        {global.hasLogin?this.getTotalPrice(price):'登录可见'}
                    </p>
                    <div className={"cart-pro-item-content-p8"}>
                        {global.hasLogin && (
                            <PopConfirm
                                content={
                                    isInteresting
                                        ? "确定取消关注吗？"
                                        : "确定移入我的关注吗？"
                                }
                                position="leftTop"
                                icon={
                                    <Icon
                                        type="exclamation-circle-fill"
                                        size="small"
                                        color="warning"
                                    />
                                }
                                onConfirm={() => this.interestProduct(sn)}
                                onCancel={() => {
                                    console.log("Cancel");
                                }}
                            >
                                <p className={"cart-pro-item-content-p8-focus"}>
                                    {isInteresting
                                        ? "取消关注"
                                        : "移入我的关注"}
                                </p>
                            </PopConfirm>
                        )}

                        <PopConfirm
                            content="确定删除商品吗?"
                            position="bottomLeft"
                            icon={
                                <Icon
                                    type="exclamation-circle-fill"
                                    size="small"
                                    color="warning"
                                />
                            }
                            onConfirm={() => this.deleteShopCart(sn)}
                            onCancel={() => {
                                console.log("Cancel");
                            }}
                        >
                            <p
                                className={
                                    global.hasLogin
                                        ? "cart-pro-item-content-p8-del"
                                        : "cart-pro-item-content-p8-del2"
                                }
                            >
                                删除
                            </p>
                        </PopConfirm>
                    </div>
                </div>
                <InfoModal getRef={this.getRef} content={modalMsg} />
            </div>
        );
    }

    getRef = v => {
        this.infoModal = v;
    };

    getTotalPrice(price) {
        const { count } = this.state;

        let totalPrice = (price - 0) * count;
        return `￥${totalPrice.toFixed(2)}`;
    }
}

class Tip extends React.Component {
    constructor() {
        super();
        this.state = {
            message: "查询中...",
            oheight: 44
        };
    }

    componentDidMount() {
        this.priceAvailability();
    }

    //获取货期西格玛
    priceAvailability() {
        let url = `/shop/store/product/priceAvailability`;
        let params = {
            productCode: this.props.id,
            quantity: this.props.carNum || 1
        };
        REST.post(url, params).then(
            data => {
                let msg = data.code == "1" ? data.data || "无" : "请重新查询";

                this.setState({ message: msg || "无" }, () => {
                    const { tip } = this.refs;
                    const oheight = tip.offsetHeight;
                    this.setState({ oheight });
                });
            },
            error => {}
        );
    }

    hide = (e, isShow) => {
        if (e.target && e.target.id !== "modalBg") {
            return;
        }
        isShow = false;
        this.props.cb && this.props.cb(isShow);
    };

    render() {
        const { message, oheight } = this.state;
        const { isShow } = this.props;
        return (
            <React.Fragment>
                <div
                    ref="tip"
                    className="h-popoverStyle-popover h-popoverStyle-main-top"
                    style={{
                        width: "240px",
                        minHeight: "44px",
                        top: `-${oheight + 20}px`,
                        left: "-93px",
                        display: "block"
                    }}
                >
                    <div
                        className="h-popoverStyle-rect"
                        style={{ left: "115px" }}
                    />
                    <div
                        className="h-popoverStyle-contentbox"
                        style={{ width: "240px", minHeight: "44px" }}
                    >
                        <div
                            className="h-popoverStyle-content"
                            dangerouslySetInnerHTML={{ __html: message }}
                        />
                    </div>
                </div>

                <div
                    onClick={this.hide.bind(this, isShow)}
                    id="modalBg"
                    className="zen_ps-fix zen_t-0 zen_b-0 zen_l-0 zen_r-0"
                    style={{ zIndex: "1000" }}
                />
            </React.Fragment>
        );
    }
}
